package org.flower.web.servlet;

import com.jspsmart.upload.*;
import org.apache.ibatis.session.SqlSession;
import org.flower.bean.CommodityClass;
import org.flower.bean.CommodityDetails;
import org.flower.dao.CommodityDetailsDao;
import org.flower.dao.impl.CommodityDetailsDaoImpl;
import org.flower.mapper.CommodityClassMapper;
import org.flower.service.CommodityDetailsService;
import org.flower.service.impl.CommodityDetailsServiceImpl;
import org.flower.utils.MyBatisUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

/**
 * 商品添加servlet
 *
 * @author Aizen
 * @date 2021/12/21
 */
@WebServlet("/manager/commodityAddServlet.shtml")
public class CommodityAddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        SqlSession sqlSessionFactory = MyBatisUtil.getSqlSessionFactory();
        CommodityClassMapper mapper = sqlSessionFactory.getMapper(CommodityClassMapper.class);
        List<CommodityClass> classList = mapper.selectByExample(null);
        sqlSessionFactory.close();
        //查询所有商品编号列过去
        CommodityDetailsDao cd = new CommodityDetailsDaoImpl();
        List<org.flower.entity.CommodityDetails> commodityDetailsList = cd.getCommodityDetails();
        request.setAttribute("commodityDetailsList",commodityDetailsList);
        request.setAttribute("classList",classList);
        request.getRequestDispatcher("addCommoidity.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.实例化smartUpload对象
        SmartUpload smart = new SmartUpload();
        //2.设置编码格式
        smart.setCharset("utf-8");
        //3.初始化
        smart.initialize(this,request,response);
        //4.上传文件
        try {
            smart.upload();
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }

        //5.获取req对象
        Request req = smart.getRequest();

        CommodityDetails c = new CommodityDetails();
        //接收参数封装对象
        String comName = req.getParameter("comName");
        c.setComname(comName);
        String content = req.getParameter("content");
        String content2 = req.getParameter("content2");
        c.setContent(content+"split"+content2);
        String outNum = req.getParameter("outNum");
        c.setOutnum(Integer.parseInt(outNum));
        String outPrice = req.getParameter("outPrice");
        c.setOutprice(Double.parseDouble(outPrice));
        String marketPrice = req.getParameter("marketPrice");
        c.setMarketprice(Double.parseDouble(marketPrice));
        String materialScience = req.getParameter("materialScience");
        c.setMaterialscience(materialScience);
        String packing = req.getParameter("packing");
        c.setPacking(packing);
        String distribution = req.getParameter("distribution");
        c.setDistribution(distribution);
        String comShowId = req.getParameter("comShowId");
        if(comShowId.equals("0")){
            CommodityDetailsDao cd = new CommodityDetailsDaoImpl();
            Integer maxNo = cd.getMaxNo();
            comShowId =  maxNo+1+"";
        }
        c.setComshowid(Integer.parseInt(comShowId));
        String classId = req.getParameter("classId");
        c.setClassid(Integer.parseInt(classId));
        String stockd = req.getParameter("stockd");
        c.setStockd(Integer.parseInt(stockd));

        Files files = smart.getFiles();
        String comimage = "";
        String detailsimage = "";

        boolean comi = false;
        boolean dei = false;
        for (int i = 0; i < files.getCount(); i++) {
            File file = files.getFile(i);

            //如果上传了文件
            if(!file.isMissing()){
                if(file.getFieldName().equals("comImage")){
                    comi = true;
                    try {
                        file.saveAs("/image/commodity/"+file.getFileName());
                        comimage += file.getFileName()+",";
                    } catch (SmartUploadException e) {
                        e.printStackTrace();
                    }
                }else if(file.getFieldName().equals("detailsImage")){
                    dei = true;
                    try {
                        file.saveAs("/image/commodity/"+file.getFileName());
                        detailsimage += file.getFileName()+",";
                    } catch (SmartUploadException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        //全部没上传
        if(!comi&&!dei){
            String[] comImages = req.getParameterValues("comImages");
            for (String img:comImages) {
                comimage += img+",";
            }
            String[] detailsImages = req.getParameterValues("detailsImages");
            for (String img:detailsImages) {
                detailsimage += img+",";
            }
        }else if(comi&&!dei){
            //1上传
            String[] detailsImages = req.getParameterValues("detailsImages");
            for (String img:detailsImages) {
                detailsimage += img+",";
            }
        }else if(!comi&&dei){
            //2上传
            String[] comImages = req.getParameterValues("comImages");
            for (String img:comImages) {
                comimage += img+",";
            }
        }

        c.setComimage(comimage);
        c.setDetailsimage(detailsimage);

        CommodityDetailsDao commodityDetailsDao = new CommodityDetailsDaoImpl();
        boolean b = commodityDetailsDao.addCommodity(c);
        if(b){
            response.getWriter().print("<script language='javascript'>alert('添加成功！');</script>");
            response.sendRedirect("commodityListServlet");
            response.getWriter().flush();
        }else{
            response.getWriter().print("<script language='javascript'>alert('添加失败！');</script>");
            response.sendRedirect("addCommoidity.jsp");
            response.getWriter().flush();
        }

    }
}
